/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var largestSumAfterKNegations = function (nums, k) {
    nums.sort((a, b) => a - b)

    let i = 0
    while (k > 0 && i< nums.length) {
        if (nums[i] < 0) {
            nums[i] = -nums[i]
            i++
            k--
        }else{
            break
        }
    }

    if(k>0){
        if(i===nums.length){
            i--
        }
        if(k%2===1){
            if(nums[i]>nums[i-1]){
                nums[i-1] = -nums[i-1]
            }else{
                nums[i] = -nums[i]
            }
        }
    }

    let sum = nums.reduce((a,b)=>a+b)
    return sum
};